package com.liushuang.waiwaiim.controller.activity;

import androidx.annotation.NonNull;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.hyphenate.chat.EMClient;
import com.liushuang.waiwaiim.R;
import com.liushuang.waiwaiim.model.Model;
import com.liushuang.waiwaiim.model.bean.UserInfo;

public class SplashActivity extends Activity {

    public static final int WHAT = 0x01;
    public static final int DELAY_MILLIS = 2000;

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (isFinishing()){
                return;
            }

            toMainOrLogin();
        }
    };

    private void toMainOrLogin() {

        Model.getInstance().getGlobalExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                //判断是否有用户在之前登录过
                if (EMClient.getInstance().isLoggedInBefore()){

                    UserInfo userInfo = Model.getInstance().getUserAccountDao().getAccountByHxId(EMClient.getInstance().getCurrentUser());

                    //虽然用户登录过，之前数据库中应该存在用户的数据，不过如果强行删除了数据库，则返回的userInfo为空
                    //即要保证登录后数据库中使用保存着用户的数据
                    if (userInfo == null){
                        Intent intent1 = new Intent(SplashActivity.this, LoginActivity.class);
                        startActivity(intent1);
                    }else {
                        //登录成功后的方法
                        Model.getInstance().loginSuccess(userInfo);

                        Intent intent2 = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(intent2);
                    }

                }else {
                    Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

                finish();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        mHandler.sendEmptyMessageDelayed(WHAT, DELAY_MILLIS);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(WHAT);
    }
}